<?php
use Illuminate\Support\Facades\View;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Redirect;
class AuthorController extends BaseController {
	
	public $restful = true;
	
	public function index() {
		return View::make('author.index')
			->with('title', 'Authors and Books')
			->with('authors', Author::orderBy('name', 'asc')->get());
	}
	
	public function view($id) {
		return View::make('author.view')
			->with('title', 'Author View Page')
			->with('author', Author::find($id));
	}
	
	public function newAuthor() {
		return View::make('author.newAuthor')
			->with('title', 'Add new author');
	}
	
	public function create() {
		$validation = Author::validate(Input::all());
		
		if ($validation->fails()) {
			return Redirect::route('newAuthor')->withErrors($validation)->withInput();
		} else {
			Author::create(array(
				'name'	=> Input::get('name'),
				'bio'	=> Input::get('bio')
			));
			
			return Redirect::route('author')
				->with('message', 'The author was created successfully!');
		}
	}

	public function edit($id) {
		return View::make('author.edit')
			->with('title', 'Edit Author')
			->with('author', Author::find($id));
	}

	public function update() {
		$id = Input::get('id');
		$validation = Author::validate(Input::all());

		if ($validation->fails()) {
			return Redirect::route('editAuthor', $id)->withErrors($validation);
		} else {
			Author::find($id)->update(array(
				'name' => Input::get('name'),
				'bio' => Input::get('bio')
			));

			return Redirect::route('authordetail', $id)
				->with('message', 'Author updated successfully!');
		}
	}

	public function delete() {
		Author::find(Input::get('id'))->delete();
		return Redirect::route('author')
			->with('message', 'The author was deleted successfully!');
	}
}